<template>
  <div>
    <a-upload
      :action="fileUrl"
      :file-list="filesList"
      :show-upload-list="true"
      @change="changeFile"
      @preview="handlePreview"
      :multiple="mult"
      :headers="setHeaders"
    >
      <a-button v-if="allowUpload">
        <UploadOutlined></UploadOutlined>上传文件
      </a-button>
    </a-upload>
  </div>
</template>
<script setup lang="ts">
import { UploadOutlined } from "@ant-design/icons-vue";
import { ref, defineProps, watch, computed, toRefs } from "vue";
import { Base64 } from "js-base64";
import type { UploadChangeParam } from "ant-design-vue";

const props = withDefaults(
  defineProps<{
    fileDatas: any;
    prefix?: string;
    num?: number;
    mult: boolean;
  }>(),
  {
    prefix: import.meta.env.VITE_APP_USER,
    num: 3,
    mult: false,
  }
);
const filesList: any = ref([]);
watch(
  () => props.fileDatas,
  (newval: any) => {
    console.log(newval);

    filesList.value = newval;
  },
  { immediate: true }
);

const setHeaders = computed(() => {
  let auth: any = localStorage.getItem("auth");
  auth = JSON.parse(auth);
  return {
    Authorization: auth.token_type + " " + auth.access_token,
  };
});
const fileUrl = computed(() => {
  return `${props.prefix}/common/uploadFile`;
});
const sourcePreview = computed(() => {
  return import.meta.env.VITE_APP_BASE_IMGURL;
});
const allowUpload = computed(() => {
  console.log(filesList.value);

  return filesList.value.length < props.num;
});
const changeFile = (info: UploadChangeParam) => {
  console.log(info);
  filesList.value = info.fileList;
  if (info.file.status === "uploading") {
    return;
  }
  if (info.file.status === "done") {
    let files = [...info.fileList];
    files = files.slice(-props.num);
    console.log(files);

    let a = files.map((item) => {
      console.log(item);

      if (item.response) {
        item = {
          uid: item.uid,
          name: item.name,
          status: item.status,
          url: item.response.msg,
        };
      }
      return item;
    });
    filesList.value = a;
  }

  // filesList.value = a;
  console.log(filesList.value);
};
const handlePreview = (url: any) => {
  const temp = Base64.encode(import.meta.env.VITE_APP_BASE_IMGURL + url);
  window.open(
    import.meta.env.VITE_APP_PREVIEW + `?url=` + encodeURIComponent(temp)
  );
};
</script>

<style scoped lang="scss">
.ant-btn {
  min-width: 88px;
  padding: 0px 12px;
  border-color: #1677ff;
  color: #1677ff;
}
::v-deep .ant-upload-list-item {
  height: 32px;
  line-height: 32px;
}
::v-deep .ant-upload-list-item:hover .ant-upload-list-item-info {
  background: #f0f5ff;
  color: #1677ff;
  .ant-upload-list-item-name {
    color: #1677ff !important;
  }
  .anticon-paper-clip {
    color: #1677ff;
  }
  .anticon-delete {
    color: #ff4d4f;
  }
}
::v-deep .ant-upload-list-text .ant-upload-list-item-name {
  color: rgba(0, 0, 0, 0.85);
}
</style>
